import { useEffect, useMemo, useState } from "react";
import { useTable } from "@/store/table.js";
import { useCounter } from "@/store/counter.js";

const Person = () => {
  const {
    increase,
    fetchGetTableData,
    tableData,
    title: tableTitle,
    setState,
    storageData,
  } = useTable();
  const {
    title: counterTitle,
    counter,
    name,
    add,
    sub,
    fetchPostContent,
    fetchGetContent,
    reSetState,
  } = useCounter();
  const [componentData, setComponentData] = useState(0);
  useEffect(() => {
    fetchGetContent({
      name: "mock",
      age: 12,
    });
    fetchPostContent({
      status: "请求状态测试",
    });
    fetchGetTableData();
  }, []);
  useEffect(() => {
    return () => {
      reSetState();
      console.log("user组件被卸载");
    };
  }, []);

  const total = useMemo(() => {
    return counter ** 2;
  }, [counter]);
  const changeState = () => {
    const tableStorage = localStorage.getItem("table-storage");
    if (tableStorage) {
      let storageTableData = JSON.parse(tableStorage).state.tableData;
      setState({ storageData: storageTableData });
    }
  };
  return (
    <div>
      <div>{counterTitle}</div>
      <div>{name}</div>
      <div>counter:{counter}</div>
      <div>counter的平方:{total}</div>
      <button onClick={() => add()}>add</button>
      <button onClick={() => sub(2)}>sub</button>
      <div>componentData:{componentData}</div>
      <button onClick={() => setComponentData((state) => state + 1)}>
        组件值加
      </button>
      <button onClick={() => increase()}>increase</button>
      <button>{tableTitle}</button>
      <button onClick={() => changeState()}>setState测试</button>
      <div>
        {tableData.map((item, index) => {
          return (
            <div key={index}>
              <span>{item.name}</span>
              <span>{item.age}</span>
            </div>
          );
        })}
      </div>
      <div>{storageData.length > 0 && storageData[0].name}</div>
    </div>
  );
};
export default Person;
